<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="handlePicture"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :http-request="handleUpload"
      :class="{disabled:fileList.length}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="showDialog">
      <img :src="dialogImageUrl" alt="">
    </el-dialog>
    <el-progress v-if="showProgrees" :percentage="percentage" style="width:146px" :show-text="false" />
  </div>

</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDJUNVx8Qf18yXEfjG9loa5KIFwMUPpRXL',
  SecretKey: 'waw1rSqxmbARRDivwgQt58LM6YUBaHbe'
})
export default {
  data() {
    return {
      showDialog: false,
      dialogImageUrl: '',
      percentage: 0,
      showProgrees: false,
      fileList: [
        { url: 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1071653346,448304805&fm=26&gp=0.jpg' }
      ]
    }
  },
  methods: {
    handlePicture(file) {
      this.showDialog = true
      this.dialogImageUrl = file.url
    },
    handleRemove(file) {
      // 筛选点击删除的那个元素
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handleChange(file, fileList) {
      this.fileList = [...fileList]
    },
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.warning('图片格式不对,请重新上传')
        return false
      }
      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('图片太大,请重新上传')
        return false
      }
      return true
    },
    handleUpload(event) {
      this.showProgrees = true
      cos.putObject({
        Bucket: '59-1305129349', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: event.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: event.file, // 上传文件对象
        onProgress: (progressData) => {
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err)
        if (!err && data.statusCode === 200) {
          this.fileList[0].url = 'http://' + data.Location
          this.fileList[0].status = 'success'
          this.$message.success('图片上传成功')
          this.showProgrees = false
        }
      })
    }
  }
}
</script>

<style scoped>
::v-deep img{
  object-fit: cover;
  width: 100%;
  max-width:100%;
}
::v-deep .el-dialog__headerbtn{
  top:9px;
}
::v-deep .disabled .el-upload--picture-card{
  display: none;
}
</style>
